<?php
/**
* Tree mapper
* 
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* 
* @copyright Copyright (c) 2008-2009 Ne8, LLC <josh.ribakoff@gmail.com>
* @license New BSD License
* @version 0.1
* @category Shuffler
* @package Shuffler_Mapper
* 
* @todo implement findRoot() method & tests
*/
class Shuffler_Mapper_Tree extends Shuffler_Mapper
{
    public function setUp()  
    {
        $this->addSingle( $this->modelName, array( 'property' => 'Parent', 'field' => 'parent_id' ) );
        parent::setUp();
    }
    
    public function findChildren( Shuffler_Model_Tree_Node_Interface $node )
    {
        return $this->findByField( 'parent_id', $node->getId() ); 
    }
    
    public function getDepth( Shuffler_Model_Tree_Node_Interface $node )
    {
        $db = $this->getReadAdapter();
        $depth = 0;
        $parent = $node->getParent();
        if( is_null( $parent ) || $parent instanceof Shuffler_Null )
        {
            return 0;
        }
        $id = $parent->getId();
        $pk = $this->primaryKey();
        while( $row = $this->findRow( $id ) )
        {
            $id = $row[0]->parent_id;
            $depth++;
        }
        return $depth;
    }
    
    public function findParent( Shuffler_Model_Tree_Node_Interface $node )
    {
        if( $id = $node->getParentId() )
        {
            return $this->find( $id );
        }
    }
    
    public function findRow( $id )
    {
        $select = $this->getReadAdapter()->select()->from( array( 'a' => $this->tableName ) )->where( $this->primaryKey() . ' = ?', $id );
        try
        {
            $rs = $this->query( $this->getReadAdapter(), $select )->fetchAll();
        }
        catch( Exception $e )
        {
            throw new Exception( 'Unable to run Zend_Query: ' . $e->getMessage() );
        }
        return $rs;
    }
    
    
}